A Switch in Time

In this recipe we explore a new way of doing script flow control with JavaScript 1.2.

Discussion

How many times have you had to write something like the following piece of script?
if(inVar == 'Aardvark')
	outVar = '1';
else
	if(inVar == 'Bat')
		outVar = '2';
	else
		if(inVar == 'Crocodile')
			outVar = '3';
		else
			outVar = '0';

It's not a very attractive style of script writing (although often necessary), and tends to march off the editing window if you indent everything to preserve the structure. This can make for hard-to-read scripts.

The JavaScript 1.2 standard offers something more friendly and readable, the switch() function:

switch(inVar) {
	case 'Aardvark':
		outVar = 1;
		break;
	case 'Bat':
		outVar = 2;
		break;
	case 'Crocodile':
		outVar = 3;
		break;
	default:
		outVar = 0;
}

The switch() function compares the value of its variable argument to the case labels inside the body of the switch, and executes whatever script code is associated with the matching label. You might miss some subtleties of this function at first glance:



Copyright ©2000 by Charles River Media, All Rights Reserved